<%--
    Document   : index
    Created on : 08/11/2010, 17:30:17
    Author     : monteiro

    Modified by thau@google.com
    10/11/2010
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@page contentType="text/html" import="java.util.*" %>
<%@page contentType="text/html" import="br.org.imazon.sad.*" %>
<%@page contentType="text/html" import="com.google.gdata.client.*" %>
<%@page contentType="text/html" import="com.google.gdata.client.Service.*" %>
<%@page contentType="text/html" import="com.google.gdata.util.*" %>
<%@page contentType="text/html" import="com.google.gdata.client.AuthTokenFactory.AuthToken" %>
<%@page contentType="text/html" import="com.google.gdata.client.GoogleAuthTokenFactory.UserToken" %>



<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Earth Engine - SAD</title>
        <link href="css/style.css" rel="stylesheet" type="text/css">
        <link href="css/datePicker.css" rel="stylesheet" type="text/css">
        <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
        <script src="http://www.google.com/jsapi?key=ABQIAAAA2eRi3dhWNr9vJqDcRa8iIRRdeckKhH_oQRJP7U_3LvUSsSvczxTanHRhggZs734oxoe38ks2Yp8VwA" type="text/javascript"></script>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript" src="OpenLayers.js"></script>
  <script type="text/javascript" src="jquery-ui-1.8.6.custom.min.js"></script>
  <!-- script type="text/javascript" src="jquery.ui.datepicker-pt-BR.js"></script -->
<script type="text/javascript">
//google.load('jquery', '1');
google.load("maps", "3", {other_params:"sensor=false"});
//google.load("jqueryui", "1.8.6");

function pressButton(element) {
  element.className = 'button depressed';
  event.stopPropagation();
  return false;
}

function releaseButton(element) {
  element.className = 'button';
  return false;
}

function getWindowSize() {
  var width = window.innerWidth;
  var height = window.innerHeight;
  if (typeof(width) === 'undefined') {  // for IE
    width = document.body.offsetWidth;
    height = document.body.offsetHeight;
  }
  return [width, height];
}

function handleWindowResize() {
  var windowHeight = getWindowSize()[1];
  var resultsTop = $('#results').offset().top;
  $('#results')[0].style.height = (windowHeight - resultsTop - 1) + 'px';
}

function initializeElements() {
  // Attach event handlers to all buttons.
  var buttons = $('.button');
  for (var i = 0; i < buttons.length; i++) {
    buttons[i].setAttribute('onmousedown', 'return pressButton(this)');
    buttons[i].setAttribute('onmouseup', 'return releaseButton(this)');
    buttons[i].setAttribute('onmouseout', 'return releaseButton(this)');
  }

  // Treat the Enter key like clicking the Search button.
  $('#query').keyup(function (event) {
    if (event.keyCode == 13) {
      searchPolygons();
    }
  });

  // Attach event handlers for all the controls that require map re-rendering.
  var inputs = $.merge($.merge($.merge([], 
      $('#reference_id select')),
      $('#date_range input')),
      $('#out_type input'));
  for (var i = 0; i < inputs.length; i++) {
    inputs[i].setAttribute('onchange', 'updateOverlay()');
  }

  // Attach event handlers for window resizing.
  var windowSize = [null, null];
  window.onresize = function () {
    var newSize = getWindowSize();
    if (newSize[0] != windowSize[0] || newSize[1] != windowSize[1]) {
      handleWindowResize();
      windowSize = newSize;
    }
  };

  handleWindowResize();
}

var TEMP_START = '9/15/2009';
var TEMP_END = '10/1/2009';
var gmap;  // base map, a google.maps.Map object
var polygonLayer;  // a FusionTablesLayer used to show the selected polygon

// This table and list, together, cache recently viewed layer objects so the
// user can flip between them instantly.  The parameters used to compute the
// layer are used to construct a "layer key"; earthEngineLayers is a table
// from layer keys to layer objects.  earthEngineRecentLayers is a list of
// layer keys, just to keep track of which are the most recently used.
var earthEngineLayers = {};  // table from layer keys to ImageMapType layers
var earthEngineRecentLayers = [];  // list of layer keys, most recent last

function initialize() {
  initializeElements();

  earthengine.BASE_URL =
      window.location.protocol + '//' + window.location.host + '/';

  //earthengine.TILE_URLS = [ earthengine.BASE_URL + 'map' ];
  earthengine.TILE_URLS = [
    'http://earthengine.googleapis.com/map',
    'http://earthengine.googleapis.com/map',
    'http://earthengine.googleapis.com/map',
    'http://earthengine.googleapis.com/map'];

  getReferenceMaps();

  var latlng = new google.maps.LatLng(-9.50, -55.670952);

  gmap = new google.maps.Map(document.getElementById("map_canvas"), {
    zoom: 5,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.SATELLITE
  });

  polygonInfoWindow = new google.maps.InfoWindow();
  
  geoJson = "";

  //gmap = new GMap2(document.getElementById("map_canvas"));
  //gmap.setCenter(new GLatLng(-9.50, -55.670952), 6);
  //gmap.addControl(new GLargeMapControl());
  //gmap.addControl(new GHierarchicalMapTypeControl());
  //gmap.enableScrollWheelZoom();
  //gmap.setMapType(G_SATELLITE_MAP);
  
 
  $(function() {
    $("#terminalTemporalMosaicStart").datepicker({defaultDate: TEMP_END});
    $("#terminalTemporalMosaicFinish").datepicker({defaultDate: TEMP_END});
    //$("#terminalTemporalMosaicStart").datepicker($.datepicker.regional['pt-BR']);
    //$("#terminalTemporalMosaicFinish").datepicker($.datepicker.regional['pt-BR']);

     $("#terminalTemporalMosaicStart" ).datepicker({
       onClose: function(dateText, inst) {
         alert("foo");
       }
     });
  });
}
</script>

<script type="text/javascript">
// takes as input begin and end dates
// should output arrays like:
//var dates1 = ['2010_03_03', '2010_03_04', '2010_03_05'];
//var dates2 = ['2010_06_28', '2010_06_29', '2010_06_30'];

var TIME_SLUSH = 43000000;  // to slightly expand the range of the time queries
function getImageNames(startTime, endTime) {

    // convert the dates to milliseconds since the epoch
    var startEpoch = new Date(startTime).getTime() - TIME_SLUSH;
    var endEpoch = new Date(endTime).getTime() + TIME_SLUSH;

    // make the EE call
    var dates = listDates(startEpoch, endEpoch);
  return dates;
}


function listDates(startEpoch, endEpoch) {
  var resultList = [];
  $.ajax({
    url: earthengine.BASE_URL + "api/list?id=MOD09GA" +
        "&starttime=" + startEpoch + "&endtime=" + endEpoch,
    success: function(result) {
      for (i = 0; i < result.data.length; i++) {
        resultList.push(result.data[i].id.split('/MOD09GA_005_')[1]);
      }
    },
    dataType: 'json',
    async: false,  // wait for all results to collect in resultList
  });
  return resultList;
}

// Populates the reference map selector with the available reference maps.
function getReferenceMaps() {
  $.get(
    earthengine.BASE_URL + "api/list?id=PRODES",
    function (result) {
      var select = $('#reference_map_select')[0];
      for (var i = 0; i < result.data.length; i++) {
        var name = result.data[i].id.split('/')[1];
        var option = $('<option>')[0];
        option.text = name.replace("_"," ");
        option.value = name;
        if (document.all && !window.opera) {
          select.options.add(option);
        } else {
          select.options.add(option, null);
        }
      }
    },
    'json'
  );
}

// Changes the displayed tile overlay to match what the user selected.
function updateOverlay() {
  // Get the reference map that the user selected.
  var referenceMap = $('#reference_map_select').val();

  // Get the date range that the user selected.
  var startDate = $('#terminalTemporalMosaicStart').val();
  var endDate = $('#terminalTemporalMosaicFinish').val();

  // Get the output type that the user selected.
  var outType;
  var buttons = $('#out_type input');
  for (var i = 0; i < buttons.length; i++) {
    if (buttons[i].checked) {
      outType = buttons[i].id;
    }
  }

  // Turn the user's selections into parameters for computing the overlay.
  var params;
  if (referenceMap && startDate && endDate && outType) {
    if (new Date(startDate) <= new Date(endDate)) {
      if (new Date(startDate) >= new Date(TEMP_END)) {
        params = getOverlayParameters(referenceMap, startDate, endDate, outType);
      } else {
        alert("Please don't start with dates before " + TEMP_END);
      }
    } else {
      alert("Your start date is after your end date.");
    }
  }
  showOverlay(params);
}

// Generate new statistics.
function updateStatistics(table, row) {

  getPolygonKML(table, row);

}

function getPolygonStatistics() {
  
  // Get the reference map that the user selected.
  var referenceMap = $('#reference_map_select').val();

  // Get the date range that the user selected.
  var startDate = $('#terminalTemporalMosaicStart').val();
  var endDate = $('#terminalTemporalMosaicFinish').val();

  // Get the output type that the user selected.
  var outType;
  var buttons = $('#out_type input');
  for (var i = 0; i < buttons.length; i++) {
    if (buttons[i].checked) {
      outType = buttons[i].id;
    }
  }

  // Turn the user's selections into parameters for computing the statistics.
  var params;
  if (referenceMap && startDate && endDate && outType) {
    params = getOverlayParameters(referenceMap, startDate, endDate, outType);
    generateStatistics(params);
  }
}

function getPolygonCenter() {
  var coords = $.parseJSON(geoJson);
  var east = coords[0][0];
  var west = coords[0][0];
  var north = coords[0][1];
  var south = coords[0][1];
  for (var i = 0; i < coords.length; i++) {
    var longitude = coords[i][0];
    var latitude = coords[i][1];
    if (latitude > north) {
      north = latitude;
    }
    if (latitude < south) {
      south = latitude;
    }
    if (longitude > east) {
      east = longitude;
    }
    if (longitude < west) {
      west = longitude;
    }
  }
  return new google.maps.LatLng((north + south)/2.0, (east + west)/2.0);
}

function generateStatistics(params) {
  polygonInfoWindow.close();

  if (params) {
    var meta = {
      image: params.image,
      fields: 'covers',
    };
    earthengine.getValue(meta, function(result) {
      var forestPixels = result.properties.covers[1];
      var forestArea = forestPixels * 900 / 1000;
      polygonInfoWindow.setContent(
          '<div class="infowindow">' +
          '<h3>' + polygons[selectedPolygon].description + '</h3>' +
          '<p>Forest area: ' + forestArea + ' km<sup>2</sup>' +
          '</div>');
      polygonInfoWindow.setPosition(getPolygonCenter());
      polygonInfoWindow.open(gmap);
    });
  }
}    
    
    
// Shows the Earth Engine tile overlay for the given parameters.
function showOverlay(params) {
  if (params) {
    // Make a unique key for the parameters that determine the overlay.
    var layerKey = $.toJSON(params);

    if (!(layerKey in earthEngineLayers)) {
      // We don't already have this layer, so we need to render it.
      earthengine.getMapId(params, function(mapId) {
        if (earthEngineRecentLayers.length > 10) {  // cache up to 10 layers
          var oldestKey = earthEngineRecentLayers.shift();  // remove from list
          delete earthEngineLayers[oldestKey];  // remove from table
        }
        earthEngineLayers[layerKey] = earthengine.makeTileLayerOverlay(mapId);
        gmap.overlayMapTypes.push(earthEngineLayers[layerKey]);  // show it
        removeAllOverlaysExcept(1);
      });
    } else {
      gmap.overlayMapTypes.push(earthEngineLayers[layerKey]);  // show it
      removeAllOverlaysExcept(1);
    }

    // Put this layer key at the end of the list; it's now the most recent.
    earthEngineRecentLayers = $.grep(
        earthEngineRecentLayers,
        function(value) { return value != layerKey; });  // remove it
    earthEngineRecentLayers.push(layerKey);  // add it to the end

  } else {
    removeAllOverlaysExcept(0);  // remove all the overlays
  }
}

// Hide all currently shown overlays except the top 'numberToKeep' of them.
function removeAllOverlaysExcept(numberToKeep) {
  // To prevent the display from flickering, allow a delay for the top
  // overlay to appear before removing the overlays below it. 
  window.setTimeout(function() {
    while (gmap.overlayMapTypes.getLength() > numberToKeep) {
      gmap.overlayMapTypes.removeAt(0);
    }
  }, 250);
}

// Constructs a series of combined image specs, given a date range.
function getCombinedImageSpecs(startDate, endDate) {
  var imageNames = getImageNames(startDate, endDate);
  var specs = [];
  for (var i = 0; i < imageNames.length; i++) {
    specs.push({
      creator: 'SAD/ModisCombiner',
      args: ['MOD09GA_005_' + imageNames[i], 'MOD09GQ_005_' + imageNames[i]]
    });
  }
  return specs;
}

// Determines the parameters for Earth Engine based on the user's selections.
function getOverlayParameters(referenceMap, startDate, endDate, outType) {
  var MODIS_BANDS = [
      'sur_refl_b01_250m', 'sur_refl_b02_250m', 'sur_refl_b03_500m',
      'sur_refl_b04_500m', 'sur_refl_b06_500m', 'sur_refl_b07_500m'];
 

  switch (outType) {
    case 'changedetection':
      //var THIS_POLY = [[[[-54,2],[-54,4],[-52,4],[-52,2]]]];
      //var THIS_POLY = [[[[-49.829811,-3.633172],[-49.835817,-3.635041],[-49.837193,-3.639221],[-49.840423,-3.643402],[-49.842845,-3.644176],[-49.848275,-3.643877],[-49.851571,-3.643363],[-49.860506,-3.645121],[-49.862204,-3.647577],[-49.863459,-3.650927],[-49.865765,-3.651569],[-49.867872,-3.654068],[-49.868574,-3.654782],[-49.8714,-3.655683],[-49.880015,-3.598965],[-49.844177,-3.592855],[-49.832001,-3.623335],[-49.829811,-3.633172]]]];
      var THIS_POLY = null
      if (geoJson.length > 0) {
        THIS_POLY = [[$.parseJSON(geoJson)]];
       } 

      var NDFI_IMAGE_1 = {
        creator: 'SAD/NDFIImage',
        args: [{
          creator: 'SAD/UnmixModis',
          args: [{
            creator: 'SAD/KrigingStub',
            args: [{
              creator: 'SAD/MakeMosaic',
              args: [getCombinedImageSpecs(TEMP_START, TEMP_END), MODIS_BANDS]
            }]
          }]
        }]
      };
      var NDFI_IMAGE_2 = {
        creator: 'SAD/NDFIImage',
        args: [{
          creator: 'SAD/UnmixModis',
          args: [{
            creator: 'SAD/KrigingStub',
            args: [{
              creator: 'SAD/MakeMosaic',
              args: [getCombinedImageSpecs(startDate, endDate), MODIS_BANDS]
            }]
          }]
        }]
      };
      var PRODES_IMAGE = {
        creator: 'SAD/ProdesImage',
        args: [referenceMap]
      };
      return {
        image: $.toJSON({
           creator: 'SAD/ChangeDetectionImage',
           args: [NDFI_IMAGE_2, NDFI_IMAGE_1, PRODES_IMAGE, THIS_POLY]
        }),
        bands: 'vis-red,vis-green,vis-blue',
        gain: 1,
        bias: 0.0,
        gamma: 1.6
      };

    case 'ndfit0':
      return {
        image: $.toJSON({
          creator: 'SAD/NDFIImage',
          args: [{
            creator: 'SAD/UnmixModis',
            args: [{
              creator: 'SAD/KrigingStub',
              args: [{
                creator: 'SAD/MakeMosaic',
                args: [getCombinedImageSpecs(TEMP_START, TEMP_END), MODIS_BANDS]
              }]
            }]
          }]
        }),
        bands: 'vis-red,vis-green,vis-blue',
        gain: 1,
        bias: 0.0,
        gamma: 1.6
      };

    case 'ndfit1':
      return {
        image: $.toJSON({
          creator: 'SAD/NDFIImage',
          args: [{
            creator: 'SAD/UnmixModis',
            args: [{
              creator: 'SAD/KrigingStub',
              args: [{
                creator: 'SAD/MakeMosaic',
                args: [getCombinedImageSpecs(startDate, endDate), MODIS_BANDS]
              }]
            }]
          }]
        }),
        bands: 'vis-red,vis-green,vis-blue',
        gain: 1,
        bias: 0.0,
        gamma: 1.6
      };

    case 'rgb':
      return {
        image: $.toJSON({
          creator: 'SAD/KrigingStub',
          args: [{
            creator: 'SAD/MakeMosaic',
            args: [getCombinedImageSpecs(startDate, endDate), MODIS_BANDS]
          }]
        }),
        bands: 'sur_refl_b01,sur_refl_b04,sur_refl_b03',
        gain: 0.1,
        bias: 0.0,
        gamma: 1.6
      };

    case 'sma':
      return {
        image: $.toJSON({
          creator: 'SAD/UnmixModis',
          args: [{
            creator: 'SAD/KrigingStub',
            args: [{
              creator: 'SAD/MakeMosaic',
              args: [getCombinedImageSpecs(startDate, endDate), MODIS_BANDS]
            }]
          }]
        }),
        bands: 'gv,soil,npv',
        gain: 256,
        bias: 0.0,
        gamma: 1.6
      };

    case 'ndfichange':
    
      var NDFI_IMAGE_1 = {
        creator: 'SAD/NDFIImage',
        args: [{
          creator: 'SAD/UnmixModis',
          args: [{
            creator: 'SAD/KrigingStub',
            args: [{
              creator: 'SAD/MakeMosaic',
              args: [getCombinedImageSpecs(TEMP_START, TEMP_END), MODIS_BANDS]
            }]
          }]
        }]
      };
      var NDFI_IMAGE_2 = {
        creator: 'SAD/NDFIImage',
        args: [{
          creator: 'SAD/UnmixModis',
          args: [{
            creator: 'SAD/KrigingStub',
            args: [{
              creator: 'SAD/MakeMosaic',
              args: [getCombinedImageSpecs(startDate, endDate), MODIS_BANDS]
            }]
          }]
        }]
      };
      
      return {
        image: $.toJSON({
           creator: 'SAD/NDFIDeltaImage',
           args: [NDFI_IMAGE_1, NDFI_IMAGE_2]
        }),
        bands: 'ndfi_delta',
        gain: 1,
        bias: 0.0,
        gamma: 1.6
      };
  }
}

// Sends a search query for polygons by name.
function searchPolygons() {
  $('#results_table').empty();
  $('#loading').show();
  $.ajax({
    url: 'search',
    data: $('#query').val(),
    dataType: 'json',
    success: handlePolygonResults,
    complete: function() { $('#loading').hide(); }
  });
}

var polygons = null;  // list of polygons returned from the last search
var polygonCells = [];  // table cells for the results of the last search
var selectedPolygon = -1;  // index in polygons[] of the selected polygon
var polygonInfoWindow = null;

// Receives the results from a search query and populates the results list.
function handlePolygonResults(results) {
  selectPolygon(-1);

  polygons = results;
  $('#results_table').empty();
  polygonCells = [];
  for (var i = 0; i < polygons.length; i++) {
    var cell = $('<td>').appendTo($('<tr>').appendTo($('#results_table')));
    cell.text(polygons[i].description);
    polygonCells.push(cell[0]);
    cell[0].setAttribute('onclick', 'selectPolygon(' + i + ')');
  }
}


function getPolygonKML(table, row) {

  var thisUrl = "choosePoly?table=" + table + "&row=" + row;
  $('#loading').show();
  $.ajax({
    url: thisUrl,
    data: $('#query').val(),
    dataType: 'json',
    success: handlePolygonKMLResults,
    complete: function() { $('#loading').hide(); }
  });
}

function handlePolygonKMLResults(results) {  
  geoJson = setPolygonGeoJson(results);
  getPolygonStatistics();
}

// Selects a polygon to show statistics for.
function selectPolygon(index) {
  // Unhighlight the old selected row.
  
  if (selectedPolygon >= 0) {
    polygonCells[selectedPolygon].className = '';
  }

  // Remove the old polygon highlight layer.
  if (polygonLayer) {
    try {
      polygonLayer.setMap(null);
    } catch (error) {
    }
  }

  if (index >= 0) {
    // Highlight the selected row.
    polygonCells[index].className = 'selected';

    // Add a new polygon highlight layer.
    var tableId = polygons[index].table_id;
    var name = polygons[index].name;
    polygonLayer = new google.maps.FusionTablesLayer(tableId, {
      query: 'SELECT geometry FROM ' + tableId + " WHERE name = '" + name + "'"
    });
    polygonLayer.setMap(gmap);
    updateStatistics(polygons[index].table_id, polygons[index].name);
  }
  
  // Update the selection state.
  selectedPolygon = index;
}

  function setPolygonGeoJson(kml) {
   
       var olInput = new
              OpenLayers.Format.KML(OpenLayers.Util.extend({extractStyles: true},
                    {}));
       var feature = olInput.read(kml);
       var output = new OpenLayers.Format.GeoJSON();
       geoJson = stripGeoJson(output.write(feature, false));
       
       return geoJson;
             
 }
 
 // we only take coordinates at this time
 function stripGeoJson(input) {
   var cutString = "\"coordinates\":";
   var coordStart = input.indexOf(cutString);
   var endPart = input.substring(coordStart+cutString.length+1);
   var closer = endPart.indexOf("]}");
   var result = endPart.substring(0,closer);  
   return result;
 }
</script>

<script type="text/javascript">
function createXMLHttpRequest(){
  // See http://en.wikipedia.org/wiki/XMLHttpRequest
  // Provide the XMLHttpRequest class for IE 5.x-6.x:
  if (typeof XMLHttpRequest == "undefined") {
    XMLHttpRequest = function() {
      try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
      try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
      try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
      try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
      throw new Error("This browser does not support XMLHttpRequest.");
    };
    return new XMLHttpRequest();
  }
}

var AJAX = createXMLHttpRequest();
function handler() {
  if (AJAX.readyState == 4 && AJAX.status == 200) {
    var json = eval(AJAX.responseText);
    for (var i = 0; i < json.length; i++) {
      addOption('temporalmosaicmapSelect',json[i],json[i]);
    }
  } else if (AJAX.readyState == 4 && AJAX.status != 200) {
    alert('Something went wrong...');
  }
}

var optn;
function addOption(selectbox, text, value) {
  optn = document.createElement("OPTION");
  optn.text = text;
  optn.value = value;
  document.getElementById(selectbox).options.add(optn);
}

function removeOption(selectbox) {
  var elSel = document.getElementById(selectbox);
  var i;

  if (elSel.length > 1) {
    for (i = elSel.length-1; i>=1; i--) {
      elSel.remove(i);
    }
  }

  elSel.options[0].selected = true;
}

// When the AJAX libraries load, also load jquery.json locally and
// then invoke our initialization function.
google.setOnLoadCallback(function() {
  $.getScript('earthengine.js', initialize);
});
</script>

  </head>
  <body>
    <div id="logo"></div>
    <div id="tagline">Powered by <a href="http://earthengine.googlelabs.com/"><img src="http://www.google.com/images/logos/google_logo_powered_by.png"> Earth Engine</a></div>
    <div id="horizontal-slish"></div>
    <!-- div id="vertical-slish"></div -->
    <!-- div id="titulo" class="titulo">Select a Time Range</div -->

    <div id="controls">

      <h2>1. Select reference map</h2>
      <div id="reference_map" class="section">
        Reference map:
        <select id="reference_map_select"></select>

      <!--
      <div id="changedetectionmap" class="validatedmap">Change Detection Map:</div>
      <select id="changedetectionmapSelect" class="changedetectionmapSelect">
      <option value="0" selected>Select Date</option>
        <%
          Calendar calendar = Calendar.getInstance();
          String today= (calendar.get(Calendar.MONTH)+1)+"/"+calendar.get(Calendar.DATE)+"/"+calendar.get(Calendar.YEAR);

          while(!today.equals("11/3/2010")){


          %>
            <option value="<%=today%>"><%=today%></option>
          <%
              calendar.add(Calendar.DAY_OF_YEAR, -1);
              today = (calendar.get(Calendar.MONTH)+1)+"/"+calendar.get(Calendar.DATE)+"/"+calendar.get(Calendar.YEAR);
              }
          %>
      </select>
  -->
      </div>

      <h2>2. Select date range for temporal mosaic</h2>
      <div id="date_range" class="section">
        Date range:
        <input type="text" id="terminalTemporalMosaicStart" size=7> to
        <input type="text" id="terminalTemporalMosaicFinish" size=7>
      </div>

      <h2>3. View output</h2>
      <div id="out_type" class="section">
        <div>
	  <input type="radio" name="maps" id="ndfit0">
	  <label for="ndfit0">NDFI t0</label>
	</div>
        <div>
          <input type="radio" name="maps" id="ndfit1">
	  <label for="ndfit1">NDFI t1</label>
	</div>
        <div>
	  <input type="radio" name="maps" id="ndfichange">
	  <label for="ndfichange">NDFI Change</label>
	</div>
        <div>
	  <input type="radio" name="maps" id="sma">
	  <label for="sma">SMA</label>
	</div>
        <div>
          <input type="radio" name="maps" id="rgb">
	  <label for="rgb">RGB</label>
	</div>
        <div>
          <input type="radio" name="maps" id="changedetection">
	  <label for="changedetection">Change Detection</label>
	</div>
      </div>

      <h2>4. Select region</h2>
      <div class="section">
        <input id="query">
        <div class="button" onclick="searchPolygons()">Search</div>
      </div>
      <div id="results">
        <table cellpadding=0 cellspacing=0 id="results_table"></table>
	<div id="loading" class="section" style="display: none">
	  Loading matches... <img src="img/loading.gif">
        </div>
      </div>
    </div>

    <div id="map_canvas"></div>
    <div class="hshadow hs1"></div>
    <div class="hshadow hs2"></div>
    <div class="hshadow hs3"></div>
    <div class="hshadow hs4"></div>
    <div class="hshadow hs5"></div>
    <div class="vshadow vs1"></div>
    <div class="vshadow vs2"></div>
    <div class="vshadow vs3"></div>
    <div class="vshadow vs4"></div>
    <div class="vshadow vs5"></div>
  </body>
</html>
